#include "play.h"
#include "game.h"
#include <QDebug>
#include <QPainter>
#include<QFile>
#include<QKeyEvent>
#include<QMessageBox>
#include <QPushButton>
#include <QEventLoop>
#include <QTimer>
//119.23.61.6
static int bombbb=0;//hero是否放炸弹判断
static int bombb=0;//enenmy是否放炸弹判断

Play::Play(QWidget *parent) : QMainWindow(parent),game(":/maps/level0.txt")
{
 resize(600,600);
 manager = new QNetworkAccessManager();

 //将数据处理函数与manager的finished信号绑定
 QObject::connect(manager, &QNetworkAccessManager::finished,
         this, [=](QNetworkReply *reply) {
             if (reply->error()) {
                 qDebug() << reply->errorString();
                 return;
             }
             QString answer = reply->readAll();
             QJsonDocument jsonResponse = QJsonDocument::fromJson(answer.toUtf8());
             QJsonObject jsonObject = jsonResponse.object();

             auto mode = jsonObject["mode"].toInt();
             if(mode == 1)
             {
                 //返回值1，为userID
                 userID = jsonObject["userID"].toString();
             }else if(mode == 2)
             {
                 game.map[game.X][game.Y]="E";
                 //返回值2，说明获取数据列表
                 QString px = "null",py = "null",bx = "null",by = "null";
                 QJsonArray jsonArray = jsonObject["operationList"].toArray();
                 foreach (const QJsonValue & value, jsonArray) {
                     QJsonObject obj = value.toObject();
                     if(obj["userID"].toString() != userID)
                     {
                            px = obj["x"].toString();
                            py = obj["y"].toString();
                            bx = obj["bx"].toString();
                            by = obj["by"].toString();
                     }
                 }
                 game.X=px.toInt();
                 game.Y=py.toInt();
                 game.Bx=bx.toInt();
                 game.By=by.toInt();
                 if(game.By!=0&&game.Bx!=0){
                     bombb=1;
                     qDebug("bombb=1");
                 }
                 game.map[game.X][game.Y]="N";
                 qDebug("enemy move%d%d",game.X,game.Y);
                 this->repaint();
                 //最后一个数据肯定是最新的
             }else if(mode == 3)
             {
                 //返回值3，提交坐标成功
                 //QMessageBox::information(this,"alert","提交坐标成功");
             }

             qDebug() << answer;
         }
     );

   //向服务器注册，获取userID

 QString url = "http://119.23.61.6:5000/getUserID";
 request.setUrl(QUrl(url));
 manager->get(request);
 //获取数据定时器
 QTimer *timer = new QTimer(this);
 connect(timer, SIGNAL(timeout()), this, SLOT(receive()));
 timer->start(100); //每一秒抓取一次数据
 //怪物行走定时器
// QTimer *testTimer = new QTimer(this);
// connect (testTimer,SIGNAL(timeout()),this,SLOT(M()));
// testTimer->start(1000);
 //hero炸弹定时器
 QTimer *testTimer2 = new QTimer(this);
 connect (testTimer2,SIGNAL(timeout()),this,SLOT(B()));
 testTimer2->start(100);
 //enemy炸弹定时器
 QTimer *testTimer3 = new QTimer(this);
 connect (testTimer3,SIGNAL(timeout()),this,SLOT(B2()));
 testTimer3->start(100);
}

//void Play::paintEvent(QPaintEvent *event)
//{
//    QPainter painter(this);
//    game.draw(painter);
//}
void Play::keyPressEvent(QKeyEvent *event)
{
    if(event->key() == Qt::Key_Up)
    {
        game.moveUp();
        send();
    }
    if(event->key() == Qt::Key_Down)
    {
        game.moveDown();
        send();
    }
    if(event->key() == Qt::Key_Right)
    {
        game.moveRight();
        send();
    }
    if(event->key() == Qt::Key_Left)
    {
        game.moveLeft();
        send();
    }
    if(event->key() == Qt::Key_W)
    {
        //game.setBomb();
        bombbb=1;
    }
    if(game.isEnd())
        QMessageBox::information(this,"提示","游戏结束");
    this->repaint();
}
void Play::paintEvent(QPaintEvent *)
{
    QPainter painter(this);
    game.draw(painter);

}
void Play::send()
{

    //按键按下，提交当前的坐标
   auto x = QString::number(game.x);
   auto y = QString::number(game.y);
   auto bx = QString::number(game.bx);
   auto by = QString::number(game.by);
   QString url = "http://119.23.61.6:5000/submit?x="+x+"&y="+y+"&bx="+bx+"&by="+by+"&userID="+userID;
   request.setUrl(QUrl(url));
   manager->get(request);

}

void Play::receive(){

    QString url = "http://119.23.61.6:5000/getOperationLists";
    request.setUrl(QUrl(url));
    manager->get(request);
    qDebug("receive");
}

void Play::Delay_MSec(unsigned int msec)
{
     QEventLoop loop;//定义一个新的事件循环
     QTimer::singleShot(msec, &loop, SLOT(quit()));//创建单次定时器，槽函数为事件循环的退出函数
     loop.exec();//事件循环开始执行，程序会卡在这里，直到定时时间到，本循环被退出
}

void Play::M(){
    game.setMonsterMap();
    game.monsterMove();
    this->repaint();
}

void Play::B(){
    if (bombbb==1){
        game.setBomb1();
        //this->repaint();
        send();
        Delay_MSec(1000);
        game.setBomb2();
        //qDebug("2");
        //this->repaint();
        Delay_MSec(1000);
        game.setBomb3();
        //qDebug("3");
        bombbb=0;
        send();
    }
}

void Play::B2(){
    if (bombb==1){
        game.map[game.Bx][game.By]='B';
        Delay_MSec(1000);
        game.setBomb2(game.Bx,game.By);
        Delay_MSec(1000);
        game.setBomb3(game.Bx,game.By);
        bombb=0;
    }

}
